package com.sinotrans.auth.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sinotrans.auth.entity.UserEntity;
import com.sinotrans.auth.repository.UserRepository;
import com.sinotrans.common.rest.Page;
import com.sinotrans.common.rest.RestEntity;
import com.sinotrans.common.security.AuthEntity;
import com.sinotrans.common.security.AuthUtils;

import io.swagger.annotations.Api;

@Api(tags = "用户接口")
@RestController
public class UserController {

	@Autowired
	private UserRepository userRepository;

	@GetMapping("/user")
	public Object currentUserNameSimple(HttpServletRequest request) {
		AuthEntity authorize = AuthUtils.getAuthorize(request);
		return userRepository.getById(authorize.getIsd());
	}

	@GetMapping("/user/{id}")
	public UserEntity getUser(@PathVariable String id) {
		return userRepository.getById(id);
	}

	@PostMapping("/user")
	public void saveOrUpdateUser(@RequestBody UserEntity user) {
		userRepository.saveOrUpdate(user);
	}

	@DeleteMapping("/user/{id}")
	public void deleteUser(@PathVariable String id) {
		userRepository.removeById(id);
	}

	@PostMapping(value = "/user/query")
	public RestEntity<List<UserEntity>> query(@RequestBody UserEntity item) {
		RestEntity<List<UserEntity>> rest = new RestEntity<>();
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>();
		queryWrapper.setEntity(item);
		List<UserEntity> list = userRepository.list(queryWrapper);
		rest.setEntity(list);
		return rest;
	}

	@PostMapping(value = "/user/page")
	public Page<UserEntity> page(@RequestBody Page<UserEntity> page) {
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>();
		queryWrapper.setEntity(page.getRecords().get(0));
		Page<UserEntity> result = userRepository.page(page, queryWrapper);
		return result;
	}

}
